package com.j.lemon.learn.thread.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author lijunjun
 * @Date 2019-04-17 18:07
 * @Description  自旋锁，指尝试获取锁的线程不会立即阻塞，而是采用循环的方式去尝试获取锁，这样的好处是减少线程上下文切换的消耗，缺点是循环会消耗CPU
 *               例子：请手写一个自旋锁。
 */
public class SpinLockDemo {

    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    private void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t come in");
        while(!atomicReference.compareAndSet(null,thread)){

        }
    }

    private void myUnlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"\t unlock");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(()->{
            spinLockDemo.myLock();
            try{
                Thread.sleep(5000);
            }catch (Exception e){
                e.printStackTrace();
            }
            spinLockDemo.myUnlock();
        },"t1").start();

        Thread.sleep(1000);

        new Thread(()->{
            spinLockDemo.myLock();
            spinLockDemo.myUnlock();
        },"t2").start();

    }
}
